import React, { Component } from 'react';
import axios from 'axios';

export default class RecordForm extends Component{
    constructor(props){
        super(props);
        this.state = {
            date: "",
            title: "",
            amount: ""
        }
    }

    valid(){
        return this.state.date && this.state.title && this.state.amount;
    }

    handleChange(e){
        const {name, value} = e.target;
        this.setState({
            [name]: value
        });
    }

    handleSubmit(e){
        e.preventDefault();
        axios.post("https://5a54227777e1d20012fa0723.mockapi.io/api/v1/records", this.state).then(
            response => {
                this.props.handleNewRecord(response.data);
                this.setState({
                    date: "",
                    title: "",
                    amount: ""
                })
            }
        ).catch(
            error => console.log(error.message)
        )
    }

    render(){
        return (
            <form className="form-inline mb-3" onSubmit={this.handleSubmit.bind(this)}>
                <div className="form-group">
                    <input onChange={this.handleChange.bind(this)} value={this.state.date} type="text" className="form-control mr-1" placeholder="Date" name="date"/>
                </div>
                <div className="form-group">
                    <input onChange={this.handleChange.bind(this)} value={this.state.title} type="text" className="form-control mr-1" placeholder="Title" name="title"/>
                </div>
                <div className="form-group">
                    <input onChange={this.handleChange.bind(this)} value={this.state.amount} type="text" className="form-control mr-1" placeholder="Amount" name="amount"/>
                </div>
                <button type="submit" className="btn btn-primary" disabled={!this.valid()}>Create Reaord</button>
            </form>
        );
    }
}